/*
* Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const { ProjectConfig } = require("../ros1/ProjectConfig");
const { PackageTool } = require("../ros_msg_utils/PackageTool");
const { RosProto } = require("../ros_msg_utils/RosProto");

class SaveRobotConfig {
    static CONFIG_FILE_NAME = "robot.config";// 配置文件名
    static VERSION = 1;
    constructor() {
        // this.runtime = {
        //     "node": {},
        //     "topic": {},
        //     "service": {},
        // };
        // this.custom = {
        //     "node": {},
        //     "message": {},
        // };
    }
    static getInstance() {
        if (!SaveRobotConfig.instance) {
            SaveRobotConfig.instance = new SaveRobotConfig();
        }
        return SaveRobotConfig.instance;
    }
    update() {
        this.needUpdate = true;
        setTimeout(() => {
            if (this.needUpdate) {
                this.saveConfig();
                this.needUpdate = false;
            }
        }, 1000);
    }
    saveConfig() {
        const { RobotManager } = require("./RobotManager");
        const { SelectRobotPart } = require("./SelectRobotPart");
        let robots = RobotManager.getInstance().robots;
        let parts = SelectRobotPart.getInstance().customParts;
        let pt = new PackageTool(null, 1024 * 1024);//配置文件不超过1M
        pt.put_uint32(SaveRobotConfig.VERSION);
        pt.put_string(JSON.stringify(robots));
        pt.put_string(JSON.stringify(parts));

        let configFilePath = ProjectConfig.WORKSPACE_PATH + "/" + ProjectConfig.PROJECT_NAME + "/" + SaveRobotConfig.CONFIG_FILE_NAME;
        RosProto.putFile(configFilePath, pt.offset[0], pt.buffer.subarray(0, pt.offset[0]));
    }
    loadConfig(cb) {
        let configFilePath = ProjectConfig.WORKSPACE_PATH + "/" + ProjectConfig.PROJECT_NAME + "/" + SaveRobotConfig.CONFIG_FILE_NAME;
        RosProto.getFile(configFilePath, (data) => {
            if (data) {
                this.parse(data);
            } else {
                this.saveConfig();
            }
            cb();
        })
    }
    parse(data) {
        const { RobotManager } = require("./RobotManager");
        const { SelectRobotPart } = require("./SelectRobotPart");
        let pt = new PackageTool(data);
        let version = pt.get_uint32();
        if (version === SaveRobotConfig.VERSION) {
            RobotManager.getInstance().robots = JSON.parse(pt.get_string());
            SelectRobotPart.getInstance().customParts = JSON.parse(pt.get_string());
        }
    }
    sendFileToProject(destDir, file, callback) {
        const reader = new FileReader();

        // 读取为ArrayBuffer (二进制数据)
        reader.readAsArrayBuffer(file);

        reader.onload = function (e) {
            const arrayBuffer = e.target.result;
            // 现在你可以处理二进制数据了
            console.log('二进制数据:', arrayBuffer);

            // 如果需要，可以转换为Uint8Array
            const uint8Array = new Uint8Array(arrayBuffer);
            console.log('Uint8Array:', uint8Array);

            let destPath = ProjectConfig.WORKSPACE_PATH + "/" + ProjectConfig.PROJECT_NAME + "/" + destDir + "/" + file.name;

            RosProto.putFile(destPath, file.size, uint8Array);

            callback(destPath);
        };

        reader.onerror = function () {
            console.error('读取文件出错');
        };
    }
}

module.exports = {
    SaveRobotConfig
}